<template>
  <div class="app-container">
    <el-drawer
      v-model="isShow"
      size="50%"
      :destroy-on-close="true"
      @close="closeHandle"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :show-close="false"
      >
          <template #header="{ close, titleId, titleClass }">
              <h4 :id="titleId" :class="titleClass">巡查记录</h4>
          </template>
      <el-image
      v-if="imgurl != ''"
      style="width: 100px; height: 100px;border:1px solid #dcdfe6"
      :src="imgurl"
      :previewSrcList="srcList" />
          <el-form :model="form"  ref="formRef" :rules="rules">
              <el-row :gutter="20">
                  <el-col :span="24" class="tittle">
                      <el-form-item label="巡查信息" label-width="100px" label-position="top" required prop="xcDetailList">
                      <el-checkbox-group v-model="form.xcDetailList" :disabled="isreadonly">
                          <el-row :gutter="20"> 
                          <el-col :span="8" v-for="(item, index) in checkboxOptions" :key="item.xcContentId">
                              <el-checkbox :label="item.name" 
                              :value="{xcContentId:item.xcContentId,name:item.name}" />
                          </el-col>
                          </el-row>
                      </el-checkbox-group>
                      </el-form-item>
                  </el-col>
                  <el-col :span="24" class="tittle" v-if="isOtherSelected">
                      <el-form-item label="勾选其他时填写" label-width="100px" label-position="top" required>
                          <el-input v-model="other" type="textarea" resize="none" :rows="3" :readonly="isreadonly" />
                      </el-form-item>
                  </el-col>
                  <el-col :span="24" class="tittle">
                      <el-form-item label="具体描述" label-width="100px" label-position="top" >
                          <el-input v-model="info" type="textarea" resize="none" :rows="3" :readonly="isreadonly" />
                      </el-form-item>
                  </el-col>
              </el-row>
          </el-form>
          <template #footer>
              <el-button type="primary" @click="submit">提交</el-button>
              <el-button @click="closedrawer" style="margin-left:20px">关闭</el-button>
          </template>
      </el-drawer>
    <el-row :gutter="20" style="height:calc(100% - 40px);">
      <!-- 四个播放器 -->
      <el-col :span="4" style="height: 500px; overflow-y:auto;">
          <div class="head-container">
              <el-tree-select
                  v-model="selectedUnitId"
                  :data="UnitOptions"
                  default-expand-all
                  :props="{ value: 'id', label: 'label', children: 'children' }"
                  value-key="id"
                  placeholder="选择单位"
                  check-strictly
                  @node-click="handleNodeClickUnit"
              />
          </div>
          <el-divider />
          <div class="head-container" v-loading="loadingdeptOptions">
                  <el-tree :data="deptOptions" 
                  :props="{ value: 'id', label: 'label', children: 'children' }"
                  :expand-on-click-node="false" 
                  :filter-node-method="filterNode" 
                  ref="deptTreeRef" node-key="id"
                  highlight-current
                  @node-click="handleNodeClick" />
          </div>
      </el-col>
      <el-col :span="17">
          <el-row :gutter="1"  style="height:100%">
              <el-col :span="12" style="height:50%;margin-bottom:1px;"
              :style="getPlayerStyle(0)" @click="click(0)" id="Player0">
                  <easy-player 
                      ref="vVideoPlayerRef0" 
                      live 
                      muted 
                      autoplay
                      :video-url="videoUrlLists[0]">
                  </easy-player>
              </el-col>
              <el-col :span="12" style="height:50%;margin-bottom:1px;" id="Player1"
              :style="getPlayerStyle(1)" @click="click(1)">
                  <easy-player 
                      ref="vVideoPlayerRef1" 
                      live 
                      muted 
                      autoplay
                      :video-url="videoUrlLists[1]">
                  </easy-player>
              </el-col>
              <el-col :span="12" style="height:50%;margin-bottom:1px;" id="Player2"
              :style="getPlayerStyle(2)" @click="click(2)">
                  <easy-player 
                      ref="vVideoPlayerRef2" 
                      live 
                      muted 
                      autoplay
                      :video-url="videoUrlLists[2]">
                  </easy-player>
              </el-col>
              <el-col :span="12" style="height:50%;margin-bottom:1px;" id="Player3"
              :style="getPlayerStyle(3)" @click="click(3)">
                  <easy-player 
                      ref="vVideoPlayerRef3" 
                      live 
                      muted 
                      autoplay
                      :video-url="videoUrlLists[3]">
                  </easy-player>
              </el-col>
          </el-row>
      </el-col>
      <!-- 操作区 -->
      <el-col :span="3">
          <el-col :span="24">
              <el-button @click="closevideo" class="mb-4">关闭监控</el-button>
          </el-col>
          <el-col :span="24">
              <el-button @click="savesnapshot" class="mb-4">巡查记录</el-button>
          </el-col>
      </el-col>
    </el-row>
    
   
  </div>
</template>

<script setup>
const {proxy} = getCurrentInstance();
  import { ElMessage } from 'element-plus'
  import { getunitDeviceChannelTree } from "@/api/ParameterSetting/Device";
  import { getChannelUrl ,ContentList,} from "@/api/videoApi/videoApi";
  import { MAINAdd ,} from "@/api/monitors/monitors";
  import {deptTreeSelectPost} from "@/api/system/user.js";
  const isShow = ref(false)
  const loading = ref(false)
  const isreadonly = ref(false)
  
  
  const form = ref({
    xcDetailList:[]
  })
  const rules = {
    xcDetailList: [{ required: true, message: "请选择巡查信息", trigger: "blur" }],
}

  const imgurl = ref('')
  const other = ref('')
  const info = ref('')
  // 视频列表
  const videoUrlLists = ref([]);

  
  const vVideoPlayerRef0 = ref()
  const vVideoPlayerRef1 = ref()
  const vVideoPlayerRef2 = ref()
  const vVideoPlayerRef3 = ref()

  const selectedUnitId = ref('')
  const UnitOptions = ref([])
  const deptOptions = ref([])
  const checkboxOptions = ref([])
  const loadingdeptOptions = ref(false)
  const srcList = ref([])
  // 计算属性，判断是否选中了“其他”选项
const isOtherSelected = computed(() => {
  return Array.isArray(form.value.xcDetailList) && 
         form.value.xcDetailList.some(item => item.name === "其他");
});
  onMounted(() => {
    getDeptTree()
    const bodydata = {}
    ContentList(bodydata).then(res => {
        const filteredData = res.data.filter(item => item.type === "1" || item.type === "2");
        checkboxOptions.value = filteredData;
    })
  })
  function getDeptTree() {
      loading.value = true
      deptTreeSelectPost({isUnit: true}).then(res => {
        UnitOptions.value  = res.data
        loading.value = false
      });
    }
  // 关闭弹框
  function closeHandle() {
    other.value = ''
    info.value = ''
    console.log("关闭了")
  }
  // 关闭 抽屉
  function closedrawer() {
    isShow.value = false
  }
  // 提交
  function submit() {
    proxy.$refs["formRef"].validate(valid => {
      if (valid) {
        const hasOther = form.value.xcDetailList.some(item => item.name === '其他');
        if(hasOther && !other.value){
          ElMessage.error("巡查问题中选择了'其他'，'勾选其他时填写'内容不能为空 ");
        }else{
          let submitDetailList = form.value.xcDetailList.map(item => {
          if (item.name === '其他') {
            return {
              ...item,
              other: other.value // 假设 this.other 是你要添加的属性值
            };
          }
          return item;
        });
        // 遍历数组，添加 info 属性并删除 name 属性
        submitDetailList.forEach(obj => {
            obj.info = info.value;
            delete obj.name;
        });
        const submitdata = {
          ...form.value,
          res:'1',
          
          xcDetailList:submitDetailList
        }
        MAINAdd(submitdata).then(res => {
          other.value = ''
          info.value = ''
          isShow.value = false
        })
        }
        
       }
    })
  }
  // 记录当前选中的播放器
  const activePlayer = ref(0);

  // 点击播放器改变样式
  const click = (index) => {
      activePlayer.value = index
  }
  // 获取播放器的样式
  const getPlayerStyle = (index) => {
    return activePlayer.value === index
      ? { border: '2px solid red' }  // 选中的播放器边框为红色
      : {};
  }

  function filterNode(value, data){
    if (!value) return true;
    return data.deptName.indexOf(value) !== -1;
  }
  
  // 播放器引用
  const vVideoPlayerRefs = [
    ref(null), ref(null), ref(null), ref(null)
  ];

  // 初始化播放器
  const initPlay = () => {
    vVideoPlayerRefs.forEach(ref => {
      const player = ref.value.getVueInstance();
      player.destroyPlayer();
      player.initPlayer();
    });
  }

  // 截图功能保存为base64
  const savesnapshot = () => {
      console.log(activePlayer.value)
      var videoElement = null
      switch (activePlayer.value) {
      case 0:
          videoElement = document.querySelector('#Player0 video'); // 获取视频元素
          break;
      case 1:
          videoElement = document.querySelector('#Player1 video'); // 获取视频元素
          break;
      case 2:
          videoElement = document.querySelector('#Player1 video'); // 获取视频元素
          break;
      case 3:
          videoElement = document.querySelector('#Player1 video'); // 获取视频元素
          break;
      default:
        ElMessage.error('播放器索引无效');
    }
    isShow.value = true
    if (videoElement) {
        const canvas = document.createElement('canvas');
        canvas.width = '400';  // 设置 canvas 尺寸与视频一致
        canvas.height = '280';
        
        const ctx = canvas.getContext('2d');
        ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height); // 绘制视频到 canvas 上
        // 将 canvas 转换为图片
        const imgData = canvas.toDataURL('image/png');
        console.log(imgData)
        imgurl.value = imgData
        srcList.value[0] = imgData
        form.value.xcpic = imgData
        
        const bodydata = {}
        ContentList(bodydata).then(res => {
            const filteredData = res.data.filter(item => item.type === "1" || item.type === "2");
            checkboxOptions.value = filteredData;
        })
    } else {
        console.error('视频元素未找到');
    }
  }

  // 关闭监控功能
  const closevideo = () => {
      console.log(activePlayer.value)
      // 关闭当前选中的播放器
      let player = null
      switch (activePlayer.value) {
      case 0:
          player = vVideoPlayerRef0.value.getVueInstance();
          player.destroyPlayer();
          break;
      case 1:
          player = vVideoPlayerRef1.value.getVueInstance();
          player.destroyPlayer();
          break;
      case 2:
          player = vVideoPlayerRef2.value.getVueInstance();
          player.destroyPlayer();
          break;
      case 3:
          player = vVideoPlayerRef3.value.getVueInstance();
          player.destroyPlayer();
          break;
      default:
        ElMessage.error('播放器索引无效');
    }
  }

  function handleNodeClickUnit(data){
    form.value = form.value || {};
    form.value.bxcunitId = data.id
    getunitDeviceChannelTreeList(data.id)
  }
  function handleNodeClick(data) {
    // 处理节点单击事件
      if(data.channelcode){
        const playerQuery = {
          deviceId:data.channelcode,
          channel:data.channels,
          monitorServerId:data.monitorserverId,
        }
     
      form.value.xcDetailList = []
      form.value.xcpic = ''
      form.value = {
        ...form.value,
        res:"0",
        xctype:'1',
        xcroomId:data.channelcode,
        xcplace:data.channelname,
      } 
      MAINAdd(form.value).then(res => {
        })
        console.log(playerQuery)
      getChannelUrl(playerQuery).then(res => {
        console.log(res)
          var mergeUrl = res.data.prefix + res.data.EasyDarwin.Body.URL
          videoUrlLists.value[activePlayer.value] = mergeUrl
          console.log(videoUrlLists.value)
          activePlayer.value = (activePlayer.value + 1) % 4;
      })
    }
    
  }
  function getunitDeviceChannelTreeList(UnitId) {
    loadingdeptOptions.value = true
    deptOptions.value = []
    getunitDeviceChannelTree(UnitId).then(res => {
      // 递归转换 roomTypes 中的结构
      const transformRoomTypes = (roomTypes) => {
        return roomTypes.map(room => {
          // 保留原有的 id 和 label，如果存在的话
          const transformedRoom = {
            ...room,
            label: room.label || room.roomname,  // 仅当 label 不存在时才使用 roomname
            id: room.id || room.roomId          // 仅当 id 不存在时才使用 roomId
          };

          if (room.baseMonitorChannels) {
            // 将 baseMonitorChannels 改为 children，并处理其中的字段
            transformedRoom.children = room.baseMonitorChannels.map(channel => {
              return {
                ...channel,
                label: channel.label || channel.channelname, // 仅当 label 不存在时才使用 channelname
                id: channel.id || channel.channelcode       // 仅当 id 不存在时才使用 channelcode
              };
            });
            delete transformedRoom.baseMonitorChannels; // 删除 baseMonitorChannels 字段
          }
          // 递归处理嵌套的 children（即 room 下的子房间）
          if (room.children && room.children.length > 0) {
            transformedRoom.children = transformRoomTypes(room.children);
          }
          return transformedRoom;
        });
      };
      if (res.data && Array.isArray(res.data) && res.data[0] && res.data[0].roomTypes) {
          var roomTypesdata = transformRoomTypes(res.data[0].roomTypes);
      } else {
          ElMessage.error('当前单位无监控节点');
          loadingdeptOptions.value = false
      }
      // var roomTypesdata = transformRoomTypes(res.data[0].roomTypes);
      // 处理 videoTypes
      if (res.data && res.data[0] && res.data[0].videoTypes) {
          let videoTypesdata = res.data[0].videoTypes;
          videoTypesdata.forEach(videoType => {
              videoType.children.forEach(channel => {
                  channel.label = channel.label || channel.channelname; // 使用 channelname 作为备选
                  channel.id = channel.monitorchannelsId || channel.channelcode; // 使用 channelcode 作为备选
              });
          });
          deptOptions.value = [
            ...roomTypesdata,
            ...videoTypesdata
          ];
      } else {
          console.error("videoTypes data is missing in the response:", res.data);
      }
      loadingdeptOptions.value = false
    });
  }
</script>

<style lang="scss" scoped>
.app-container {
  height: calc(100vh - 84px);
}

#video-player-box {
  height: 500px;
}
.operation-box {
  margin-top: 10px;
}
.player-content{height: 100%;}
</style>
